<template>
	<view>
		<h-dark :title="t('language.language')" backgroundColor="#1B1F45"></h-dark>
		<view class="mx-[120rpx] my-[30rpx]">
			<u-image width="100%" mode="widthFix" src="/static/images/common/country.png" alt="" />
		</view>
		
		<view class="py-[20rpx] mx-[30rpx]">
			<view class="flex justify-around px-[40rpx] py-[35rpx] bg-[#2C326B] rounded-lg mb-[20rpx]" v-for="(item, index) in data.list" @click="langChange(item)">
				<view class="w-4/5">
					{{item.name}}
				</view>
				<view class="w-1/5 text-right">
					<u-icon v-if="!loading && item.symbol==data.lang_name" name="checkbox-mark"></u-icon>
					<u-loading v-if="loading && item.symbol==data.lang_name" mode="flower"></u-loading>
				</view>
			</view>
		</view>
	</view>
</template>

<script lang="ts" setup>
	import { onLoad } from '@dcloudio/uni-app'
	import { reactive, ref } from 'vue'
	import { getLangAll, getLangPag } from '@/api/lang'
	import { t } from '@/utils/util'
	uni.setNavigationBarTitle({ title: t('language.language') })

	const loading = ref(false)
	const data = reactive({
		lang_name: uni.getStorageSync('lang'),
		list: []
	})
	const langChange = (item : any) => {
		loading.value = true;
		data.lang_name = item.symbol;
		uni.setStorageSync('lang', item.symbol)
		uni.setStorageSync('formatTime', item.time_format)

		getPags()
		const current = getCurrentPages();
		let prevPageRoute = '';

		if (current.length >= 2) {
			let prevPage = current[current.length - 2];
			prevPageRoute = "/" + prevPage.route; // 上一个页面的路由
		}

		setTimeout(() => {
			/*#ifdef H5*/
			if (current && current.length > 1) {
				uni.reLaunch({
					url: prevPageRoute// 替换为你的页面路径
				});
			} else {
				history.back();
			}
			/*#endif*/

			/*#ifdef APP-PLUS*/
			uni.reLaunch({
				url: prevPageRoute// 替换为你的页面路径
			});
			/*#endif*/
		}, 3000);


	}
	const getPags = async () => {
		const pag = await getLangPag({ 'lang': uni.getStorageSync('lang') })
		pag.forEach((item : any) => {
			//先销毁再重新赋值
			uni.removeStorageSync(item.type + '.' + item.name);
			uni.setStorageSync(item.type + '.' + item.name, item.value);
		});
	}

	const getData = async () => {
		const apiData = await getLangAll()
		data.list = apiData;
	}
	onLoad(() => {
		getData()
	})
</script>

<style lang="scss">
</style>